package com.cmas.manage.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cmas.common.core.domain.entity.SysUser;
import com.cmas.common.utils.SecurityUtils;
import com.cmas.manage.domain.ActUser;
import com.cmas.manage.mapper.ActUserMapper;
import com.cmas.manage.vo.CollegeScore;
import com.cmas.system.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.cmas.manage.bo.ActivityAddBo;
import com.cmas.manage.bo.ActivityQueryBo;
import com.cmas.manage.bo.ActivityEditBo;
import com.cmas.manage.domain.Activity;
import com.cmas.manage.mapper.ActivityMapper;
import com.cmas.manage.vo.ActivityVo;
import com.cmas.manage.service.IActivityService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 活动Service业务层处理
 *
 * @author cmas
 * @date 2021-05-03
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {

    @Autowired
    private ActUserMapper actUserMapper;

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    @Override
    public ActivityVo queryById(Long id) {
        Activity db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, ActivityVo.class);
    }

    @Override
    public List<ActivityVo> queryList(ActivityQueryBo bo) {
        LambdaQueryWrapper<Activity> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getName()), Activity::getName, bo.getName());
        lqw.eq(StrUtil.isNotBlank(bo.getIntroduction()), Activity::getIntroduction, bo.getIntroduction());
        lqw.eq(bo.getUserId() != null, Activity::getUserId, bo.getUserId());
        lqw.eq(StrUtil.isNotBlank(bo.getAddress()), Activity::getAddress, bo.getAddress());
        lqw.eq(bo.getCommunityId() != null, Activity::getCommunityId, bo.getCommunityId());
        lqw.eq(bo.getActState() != null, Activity::getActState, bo.getActState());
        lqw.eq(StrUtil.isNotBlank(bo.getImgUrl()), Activity::getImgUrl, bo.getImgUrl());
        lqw.eq(bo.getStartTime() != null, Activity::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, Activity::getEndTime, bo.getEndTime());
        return entity2Vo(this.list(lqw));
    }

    @Override
    public List<Activity> queryListVo(Activity activity) {
        return activityMapper.queryListVo(activity);
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<ActivityVo> entity2Vo(Collection<Activity> collection) {
        List<ActivityVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, ActivityVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<Activity> page = (Page<Activity>) collection;
            Page<ActivityVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(ActivityAddBo bo) {
        bo.setUserId(SecurityUtils.getUserId());
        Activity add = BeanUtil.toBean(bo, Activity.class);
        validEntityBeforeSave(add);
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(ActivityEditBo bo) {
        Activity update = BeanUtil.toBean(bo, Activity.class);
        validEntityBeforeSave(update);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Activity entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    public int joinAct(ActUser actUser) {
        // 当前登录用户
        Long userId = SecurityUtils.getUserId();
        Long activityId = actUser.getActivityId();
        ActUser joinUser = actUserMapper.selectOne(new QueryWrapper<ActUser>().eq("activity_id", activityId).eq("user_id", userId));
        if (joinUser != null) {
            return 0;
        }
        ActUser actUser1 = new ActUser();
        actUser1.setActivityId(activityId);
        actUser1.setUserId(userId);
        actUser1.setTeacherId(actUser.getTeacherId());
        return actUserMapper.insert(actUser1);
    }

    @Override
    public List<ActUser> getActUsers(Long cid) {
        return actUserMapper.getActUsers(cid);
    }

    @Override
    public int updateActState(Long actId) {
        Activity activity = new Activity().setId(actId).setActState(2);
        return activityMapper.updateById(activity);
    }

    @Override
    public int scoring(List<ActUser> list) {
        list.forEach(item -> {
            actUserMapper.updateById(item);
        });
        return 1;
    }

    /**
     * 获取活动结果
     *
     * @param id
     * @return
     */
    @Override
    public List<CollegeScore> getCollegeActResult(Long id) {
        List<Long> userIds = sysUserMapper.selectUserListByDept(id);
        if (userIds.size() > 0) {
            return actUserMapper.getActUsersByUserId(userIds);
        }
        return new ArrayList<CollegeScore>();
    }

    /**
     * 获取活动结果
     *
     * @return
     */
    @Override
    public List<CollegeScore> getAllActResult() {
        return actUserMapper.getAllActUsers();
    }
}
